import styles from './index.module.less';
import { useEffect, useState } from 'react';
import { getYuanGong, positionNums } from '@/utils/helper';
import { useRef } from 'react';
import { Button, message, Tooltip } from 'antd';
import { ProTable, ProColumns } from '@ant-design/pro-components';
import { contractApi, positionsApi, userListApi, yiJianPingCangApi } from '@/api';
import { formatNum, getUsdtNum, isSuccess, numNoSiWu, setDefEmployeeId } from '@/utils';
import PositionType from './PositionType';
import { ZhiYingDom } from './ZhiYingSunCpn';
import { yuanGongLie } from './ComonOrder';
import { YSXYingKui } from './CommonCpn';

export default function Position() {
  const tableRef: any = useRef('');
  const [contractList, setContractList] = useState<any>(null);
  const [list, setList] = useState<any>([]);
  const [yuanGongs, setYuanGongs] = useState<any>([]);
  const [defYuanGongId, setDefYuanGongId] = useState<any>('');
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);

  useEffect(() => {
    initYuanGong();
  }, []);

  useEffect(() => {
    if (!contractList) return;
    const _list = list.map((item: any) => ({
      ...item,
      ...positionNums(item, contractList),
    }));
    setList(_list);
  }, [contractList]);

  // 请求
  const request = async (e: any) => {
    const userIds = e?.yuanGongId ? [e?.yuanGongId] : Object.keys(yuanGongs);
    const params = {
      holding: true,
      userIds,
    };
    const res: any = await positionsApi(params);
    if (!isSuccess(res)) return { data: [], total: 0 };
    const list = res?.data.map((item: any, i: number) => ({
      ...item,
      id: i + 1,
      baoZhengJin: Number(item?.leverage !== '0' ? item?.margin : item?.initial_margin), //保证金
    }));
    getContracts(res?.data.map((item: any) => item?.contract));
    const _total = list.length;
    setTotal(_total);
    return { data: list, total: _total, success: true };
  };

  // 减仓dom
  const JianCangDom = ({ num }: any) => (
    <div className={styles.jianCangWrap}>
      {[1, 2, 3, 4, 5].map((item: any, i: number) => (
        <div className={`${styles.jitem} ${num >= item && styles.jitemAct}`} key={i}></div>
      ))}
    </div>
  );

  const columns: any[] = [
    {
      title: '员工(id)',
      dataIndex: 'userName',
      hideInSearch: true,
      render: (text: any, record: any) => (
        <>
          {text}({record?.userId})
        </>
      ),
    },
    {
      title: '合约',
      dataIndex: 'serveName',
      render: (text: any, record: any) => <PositionType record={record} />,
      hideInSearch: true,
    },
    {
      title: '数量',
      dataIndex: 'size',
      hideInSearch: true,
      render: (text: any, record: any) => (
        <div>
          <Tooltip title={`持仓张数:${text} 张`}>{getUsdtNum(record)} USDT</Tooltip>
        </div>
      ),
    },
    yuanGongLie(yuanGongs, defYuanGongId, true),
    {
      title: '开仓均价',
      dataIndex: 'entry_price',
      hideInSearch: true,
    },
    {
      title: '标记价格',
      dataIndex: 'jjj',
      hideInSearch: true,
      render: (text: any, record: any) => (
        <>{contractList && formatNum(contractList[record?.contract]?.index_price)}</>
      ),
    },
    // {
    //   title: '预估强平价',
    //   dataIndex: 'qingPingJia',
    //   hideInSearch: true,
    // },
    // {
    //   title: '盈亏平衡价',
    //   dataIndex: 'serveName',
    // },
    {
      title: '保证金',
      dataIndex: 'baoZhengJin',
      render: (text: any, record: any) => <>{numNoSiWu(text)}</>,
      hideInSearch: true,
    },
    // {
    //   title: '保证金率(MMR)',
    //   dataIndex: 'serveName',
    // },
    {
      title: '未实现盈亏(回报率)',
      dataIndex: 'unrealised_pnl',
      hideInSearch: true,
      render: (text: any, record: any) => (
        <p
          key="bzj"
          className={`${record?.weiShiXianYingKui?.num > 0 ? 'color-red' : 'color-green'}`}
        >
          {record?.weiShiXianYingKui?.num?.toFixed(2)} USDT (
          {(record?.weiShiXianYingKui?.huiBaoLv * 100)?.toFixed(2)}%)
        </p>
      ),
    },
    YSXYingKui(),
    {
      title: '仓位止盈/止损',
      dataIndex: 'serveName',
      hideInSearch: true,
      render: (text: any, record: any) => (
        <ZhiYingDom
          record={record}
          type="all"
          // zhiYingDomClick={() => zhiYingDomClick('all', record)}
        />
      ),
    },
    {
      title: '部分仓位止盈/止损',
      dataIndex: 'serveName',
      hideInSearch: true,
      render: (text: any, record: any) => (
        <ZhiYingDom
          record={record}
          type="bufen"
          // zhiYingDomClick={() => zhiYingDomClick('bufen', record)}
        />
      ),
    },
    {
      title: '自动减仓', // 5最低
      dataIndex: 'adl_ranking',
      hideInSearch: true,
      render: (text: any, record: any) => [<JianCangDom num={6 - text} key="jc" />],
    },
  ];

  // 所有合约
  async function getContracts(list: any) {
    const arr = list.map((item: any) => getContract(item));
    const res: any = await Promise.allSettled(arr);
    const _list = res
      .filter((item: any) => item?.status === 'fulfilled')
      .map((item: any) => item?.value);
    const obj: any = {};
    _list.forEach((item: any) => {
      obj[item?.name] = {
        ...item,
        quanto_multiplier: Number(item?.quanto_multiplier),
        taker_fee_rate: Number(item?.taker_fee_rate),
      };
    });
    setContractList(obj);
  }

  async function getContract(contract: any) {
    const res: any = await contractApi({ contract });
    return res?.data;
  }

  // 员工列表
  const initYuanGong = async () => {
    const yuanGongs: any = await getYuanGong(userListApi);
    setYuanGongs(yuanGongs);
    // setDefYuanGongId(setDefEmployeeId(yuanGongs));
  };

  // 一键平仓
  async function yiJianPingCang() {
    setLoading(true);
    const res: any = await yiJianPingCangApi();
    setLoading(false);
    console.log('res: 一键平仓', res);
    message.success('一键平仓成功');
    tableRef.current?.reload();
  }

  return (
    <div className={styles.PositionCpn}>
      <Button type="primary" onClick={yiJianPingCang} loading={loading} disabled={total === 0}>
        一键平仓
      </Button>
      {yuanGongs && Object.keys(yuanGongs).length > 0 && (
        <ProTable
          rowKey="id"
          columns={columns}
          request={request}
          actionRef={tableRef}
          options={false}
          scroll={{ x: 1300 }}
          pagination={false}
        />
      )}
    </div>
  );
}
